package com.liao.liaowenlong;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

import com.liao.liaowenlong.service.MyService;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private Button btn_star;
    private Button btn_bind;
    private Button btn_unbind;
    private Button btn_cancel;

    private MyService.MyBind mBind;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: ");
            mBind = (MyService.MyBind) service;
            mBind.setCount(0);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        new MyOpenHelper(this).getWritableDatabase();
    }

    private void initView() {
        btn_star = (Button) findViewById(R.id.btn_star);
        btn_bind = (Button) findViewById(R.id.btn_bind);
        btn_unbind = (Button) findViewById(R.id.btn_unbind);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);

        btn_star.setOnClickListener(this);
        btn_bind.setOnClickListener(this);
        btn_unbind.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
    }

    Intent intent;

    @Override
    public void onClick(View v) {
        intent = new Intent(this, MyService.class);
        switch (v.getId()) {
            case R.id.btn_star:
                startService(intent);
                break;
            case R.id.btn_bind:
                bindService(intent, connection, BIND_AUTO_CREATE);
                break;
            case R.id.btn_unbind:
                unbindService(connection);
                break;
            case R.id.btn_cancel:
                stopService(intent);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (intent != null) {
            stopService(intent);
        }
    }
}
